/**
 * Copyright (c) 2009  Collaborative Development Group, C.S. Dept., University of Bari
 *
 * All rights reserved. This program and the accompanying materials are made available under
 * the terms of the Eclipse Public License v1.0  which accompanies this distribution, and is 
 * available at http://www.eclipse.org/legal/epl-v10.html
 */
package it.uniba.di.cdg.jtalk.internal;

import org.osgi.service.log.LogService;

import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;

import it.uniba.di.cdg.jtalk.IApplicationFacade;
import it.uniba.di.cdg.jtalk.core.IPreferenceManager;
import it.uniba.di.cdg.jtalk.core.IUserSession;
import it.uniba.di.cdg.jtalk.core.LoginFailedException;
import it.uniba.di.cdg.jtalk.ui.ChatPerspective;
import it.uniba.di.cdg.penelope.ui.lnf.IEclipseUIHelper;

/**
 * Application Facade orchestrates the high level interaction between application components.
 */
@Singleton
public class ApplicationFacade implements IApplicationFacade {

	private final Provider<IUserSession> sessionProvider;
	private final LogService logger;
	private final IEclipseUIHelper eclipseUIHelper;
		
	private IUserSession currentSession;
	private IPreferenceManager preferences;
	
	@Inject
	public ApplicationFacade( Provider<IUserSession> sessionProvider, LogService logger, IEclipseUIHelper eclipseUIHelper, IPreferenceManager preferences ) {
		super();
		this.sessionProvider = sessionProvider;
		this.logger = logger;
		this.eclipseUIHelper = eclipseUIHelper;
		this.preferences = preferences;
	}

	/* (non-Javadoc)
	 * @see it.uniba.di.cdg.jtalk.IApplicationFacade#logIn(java.lang.String, java.lang.String, boolean, boolean)
	 */
	@Override
	public void logIn( String userName, String password, boolean rememberPassword, boolean automaticLogin ) throws LoginFailedException {
		if (currentSession == null) {
			currentSession = sessionProvider.get();
		}
		currentSession.logIn( userName, password );
		
		preferences.setRememberPassword( rememberPassword );
		preferences.setAutomaticLogin( automaticLogin );
		
		eclipseUIHelper.switchPerspective( ChatPerspective.PERSPECTIVE_ID );
	}

	/* (non-Javadoc)
	 * @see it.uniba.di.cdg.jtalk.core.IApplicationFacade#logOff()
	 */
	@Override
	public void logOff() {
		if (currentSession == null || !currentSession.isLoggedIn()) {
			return;
		}
		currentSession.logOff();
		currentSession = null;
	}
}
